<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>GitHub Rate Limit Checker</title>
  <style>
* {
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  background: #f6f8fa;
  color: #24292f;
  line-height: 1.6;
}

h1 {
  color: #24292f;
  margin-bottom: 10px;
  font-weight: 600;
  font-size: 32px;
}

.instructions {
  background: #ddf4ff;
  border-left: 4px solid #0969da;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 6px;
  color: #0969da;
}

.auth-section {
  background: #ffffff;
  border-radius: 6px;
  border: 1px solid #d0d7de;
  padding: 20px;
  margin-bottom: 20px;
  text-align: center;
}

.results {
  background: #ffffff;
  border-radius: 6px;
  border: 1px solid #d0d7de;
  padding: 20px;
  margin-bottom: 20px;
}

.results h2 {
  margin-top: 0;
  color: #24292f;
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 15px;
}

.rate-limit-card {
  background: #ffffff;
  border: 1px solid #d0d7de;
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 12px;
  transition: box-shadow 0.2s;
}

.rate-limit-card:hover {
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.resource-name {
  font-weight: 600;
  color: #24292f;
  font-size: 16px;
}

.remaining-count {
  font-size: 14px;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}

.progress-container {
  width: 100%;
  height: 24px;
  background: #f6f8fa;
  border-radius: 6px;
  overflow: hidden;
  margin-bottom: 12px;
  border: 1px solid #d0d7de;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #2da44e 0%, #26a148 100%);
  transition: width 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-size: 12px;
  font-weight: 600;
  min-width: 0;
}

.progress-bar.warning {
  background: linear-gradient(90deg, #bf8700 0%, #9a6700 100%);
}

.progress-bar.critical {
  background: linear-gradient(90deg, #d1242f 0%, #cf222e 100%);
}

.progress-text {
  white-space: nowrap;
  padding: 0 8px;
}

.card-stats {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  font-size: 13px;
  color: #57606a;
}

.stat-item {
  flex: 1;
}

.stat-label {
  display: block;
  font-size: 11px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 4px;
}

.stat-value {
  display: block;
  color: #24292f;
  font-variant-numeric: tabular-nums;
}

.number {
  font-variant-numeric: tabular-nums;
}

.warning {
  color: #9a6700;
  font-weight: 600;
}

.critical {
  color: #cf222e;
  font-weight: 600;
}

button {
  padding: 10px 20px;
  background: #2da44e;
  color: #ffffff;
  border: 1px solid rgba(27, 31, 36, 0.15);
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

button:hover {
  background: #2c974b;
}

button:active {
  background: #298e46;
}

button:disabled {
  background: #94d3a2;
  cursor: not-allowed;
}

.error {
  background: #ffebe9;
  border-left: 4px solid #cf222e;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 6px;
  color: #cf222e;
}

#authLink {
  color: #0969da;
  cursor: pointer;
  text-decoration: underline;
  background: none;
  border: none;
  padding: 0;
  font-size: inherit;
  display: inline;
}

#authLink:hover {
  color: #0550ae;
}

.timestamp {
  color: #57606a;
  font-size: 12px;
  font-style: italic;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #d0d7de;
  text-align: right;
}

@media (max-width: 768px) {
  body {
    padding: 10px;
  }

  h1 {
    font-size: 24px;
  }

  .rate-limit-card {
    padding: 12px;
  }

  .resource-name {
    font-size: 14px;
  }

  .card-stats {
    flex-direction: column;
    gap: 8px;
  }
}
  </style>
</head>
<body>
  <h1>GitHub Rate Limit Checker</h1>

  <div class="instructions">
    <strong>Instructions:</strong> Authenticate with GitHub to check your API rate limits. This helps you monitor your remaining API calls.
  </div>

  <div class="auth-section" id="authSection">
    <p>Please authenticate with GitHub to check your rate limits.</p>
    <button id="authLink">Authenticate with GitHub</button>
  </div>

  <div id="checkSection" style="display: none; text-align: center; margin-bottom: 20px;">
    <button id="checkRateLimitBtn">Check Rate Limit</button>
  </div>

  <div id="results"></div>

<script type="module">
const authSection = document.getElementById('authSection');
const checkSection = document.getElementById('checkSection');
const authLink = document.getElementById('authLink');
const checkRateLimitBtn = document.getElementById('checkRateLimitBtn');
const resultsDiv = document.getElementById('results');

function checkGithubAuth() {
  const token = localStorage.getItem('GITHUB_TOKEN');

  if (token) {
    authSection.style.display = 'none';
    checkSection.style.display = 'block';
  } else {
    authSection.style.display = 'block';
    checkSection.style.display = 'none';
  }
}

function startAuthPoll() {
  const pollInterval = setInterval(() => {
    if (localStorage.getItem('GITHUB_TOKEN')) {
      checkGithubAuth();
      clearInterval(pollInterval);
    }
  }, 1000);
}

function formatTimestamp(unixTimestamp) {
  const date = new Date(unixTimestamp * 1000);
  return date.toLocaleString();
}

function formatTimeRemaining(unixTimestamp) {
  const now = Date.now();
  const resetTime = unixTimestamp * 1000;
  const diff = resetTime - now;

  if (diff <= 0) {
    return 'now';
  }

  const minutes = Math.floor(diff / 60000);
  const seconds = Math.floor((diff % 60000) / 1000);

  if (minutes > 60) {
    const hours = Math.floor(minutes / 60);
    const remainingMinutes = minutes % 60;
    return `${hours}h ${remainingMinutes}m`;
  }

  return `${minutes}m ${seconds}s`;
}

function getRemainingClass(remaining, limit) {
  const percentage = (remaining / limit) * 100;

  if (percentage <= 10) {
    return 'critical';
  } else if (percentage <= 25) {
    return 'warning';
  }

  return '';
}

async function checkRateLimit() {
  const token = localStorage.getItem('GITHUB_TOKEN');
  if (!token) {
    checkGithubAuth();
    return;
  }

  try {
    checkRateLimitBtn.disabled = true;
    checkRateLimitBtn.textContent = 'Checking...';
    resultsDiv.innerHTML = '';

    const response = await fetch('https://api.github.com/rate_limit', {
      headers: {
        'Authorization': `token ${token}`,
      }
    });

    if (!response.ok) {
      if (response.status === 401 || response.status === 403) {
        localStorage.removeItem('GITHUB_TOKEN');
        checkGithubAuth();
        resultsDiv.innerHTML = '<div class="error">Authentication failed. Please authenticate again.</div>';
        return;
      }
      throw new Error(`Failed to fetch rate limit: ${response.status} ${response.statusText}`);
    }

    const data = await response.json();

    // Create cards container
    const resultsContainer = document.createElement('div');
    resultsContainer.className = 'results';

    const header = document.createElement('h2');
    header.textContent = 'GitHub API Rate Limits';
    resultsContainer.appendChild(header);

    const cardsContainer = document.createElement('div');
    cardsContainer.id = 'cardsContainer';
    resultsContainer.appendChild(cardsContainer);

    const timestamp = document.createElement('div');
    timestamp.className = 'timestamp';
    timestamp.textContent = `Last checked: ${new Date().toLocaleString()}`;
    resultsContainer.appendChild(timestamp);

    resultsDiv.appendChild(resultsContainer);

    // Display each resource type
    const resources = data.resources;
    for (const [resourceType, resourceData] of Object.entries(resources)) {
      const limit = resourceData.limit;
      const remaining = resourceData.remaining;
      const used = resourceData.used;
      const reset = resourceData.reset;
      const remainingClass = getRemainingClass(remaining, limit);

      const usedPercentage = (used / limit) * 100;
      const resetsAt = formatTimestamp(reset);
      const resetsIn = formatTimeRemaining(reset);

      const card = document.createElement('div');
      card.className = 'rate-limit-card';
      card.innerHTML = `
        <div class="card-header">
          <span class="resource-name">${resourceType}</span>
          <span class="remaining-count ${remainingClass}">${remaining.toLocaleString()} left</span>
        </div>
        <div class="progress-container">
          <div class="progress-bar ${remainingClass}" style="width: ${usedPercentage}%">
            <span class="progress-text">${used.toLocaleString()} / ${limit.toLocaleString()} used</span>
          </div>
        </div>
        <div class="card-stats">
          <div class="stat-item">
            <span class="stat-label">Limit</span>
            <span class="stat-value number">${limit.toLocaleString()}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">Resets At</span>
            <span class="stat-value">${resetsAt}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">Resets In</span>
            <span class="stat-value">${resetsIn}</span>
          </div>
        </div>
      `;

      cardsContainer.appendChild(card);
    }

  } catch (error) {
    console.error('Rate limit check failed:', error);
    resultsDiv.innerHTML = `<div class="error">Failed to check rate limit: ${error.message}</div>`;
  } finally {
    checkRateLimitBtn.disabled = false;
    checkRateLimitBtn.textContent = 'Check Rate Limit';
  }
}

authLink.addEventListener('click', () => {
  window.open('https://tools.simonwillison.net/github-auth', 'github-auth', 'width=600,height=800');
  startAuthPoll();
});

checkRateLimitBtn.addEventListener('click', checkRateLimit);

// Check auth status on page load
checkGithubAuth();
</script>
</body>
</html>
